package admin

import (
	"fmt"
	"ginBasic/app/common/business"
	"ginBasic/app/common/lib"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"

	"ginBasic/app/common/model"
)

type LoginController struct {
	BaseController
}

// 登录页
func (con LoginController) Index(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/login/login.html", gin.H{})
}

// 操作登录
func (con LoginController) DoLogin(c *gin.Context) {
	if c.Request.Method != "POST" {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "请求方式有误",
		})
		return
	}
	var req *model.Login
	// 获取参数并验证
	if err := c.ShouldBind(&req); err != nil {
		// 返回错误信息
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "登录有误",
		})
		return
	}
	//检验验证码
	verifyRes := lib.VerifyCaptcha(req.CaptchaId, req.Captcha)
	if !verifyRes {
		// 返回错误信息
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "验证码校验有误",
		})
		return
	}

	//登录操作
	flag, msg := business.Login.DoLogin(*req, c)
	if !flag {
		// 返回错误信息
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  msg,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  msg,
	})
	return
}

// 获取验证码
func (con LoginController) Captcha(c *gin.Context) {
	id, b64s, err := lib.MakeCaptcha(50, 100, 2)
	if err != nil {
		fmt.Println(err)
	}
	c.JSON(http.StatusOK, gin.H{
		"captchaId":    id,
		"captchaImage": b64s,
	})
}

func (con LoginController) LoginOut(c *gin.Context) {
	session := sessions.Default(c)
	session.Delete("userinfo")
	session.Save()
	c.Redirect(302, "/admin/login")
}
